package com.cp.springsecuritylogin;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @author ChengPeng
 * @create 2020-04-24 10:49
 */
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    PasswordEncoder passwordEncoder(){
        return NoOpPasswordEncoder.getInstance();
    }

    @Override
    protected  void configure(AuthenticationManagerBuilder auth) throws Exception{
        auth.inMemoryAuthentication()
                .withUser("cphsw")
                .password("123").roles("admin");
    }

    @Override
    public void configure(WebSecurity web) throws Exception{
        //用来配置忽略掉的 URL 地址，一般对于静态文件，我们可以采用此操作。
        web.ignoring().antMatchers("/js/**", "/css/**","/images/**");
    }

    @Override
    //如果我们使用 XML 来配置 Spring Security ，里边会有一个重要的标签 <http>，HttpSecurity 提供的配置方法 都对应了该标签。
    protected void configure(HttpSecurity http) throws Exception{
        //authorizeRequests 对应了 <intercept-url>。
        http.authorizeRequests()
                .anyRequest().authenticated()
                .and()
                //formLogin 对应了 <formlogin>。
                .formLogin()
                .loginPage("/login.html")
                //permitAll 表示登录相关的页面/接口不要被拦截。
                .permitAll()
                //and 方法表示结束当前标签，上下文回到HttpSecurity，开启新一轮的配置。
                .and()
                //最后记得关闭 csrf
                .csrf().disable();
    }
}
